const WXAPI = require('wxapi/main')
App({
  navigateToLogin: false,
  onLaunch: function() {
    const that = this;
    // 检测新版本
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    /**
     * 初次加载判断网络情况
     * 无网络状态下根据实际情况进行调整
     */
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType
        if (networkType === 'none') {
          that.globalData.isConnected = false
          wx.showToast({
            title: '当前无网络',
            icon: 'loading',
            duration: 2000
          })
        }
      }
    });
    /**
     * 监听网络状态变化
     * 可根据业务需求进行调整
     */
    wx.onNetworkStatusChange(function(res) {
      if (!res.isConnected) {
        that.globalData.isConnected = false
        wx.showToast({
          title: '网络已断开',
          icon: 'loading',
          duration: 2000,
          complete: function() {
            that.goStartIndexPage()
          }
        })
      } else {
        that.globalData.isConnected = true
        wx.hideToast()
      }
    });
    //  获取商城名称

    WXAPI.queryConfigBatch('mallName,recharge_amount_min,share_profile').then(function(res) {
      if (res.type == 'success') {
        res.resultData.rows.forEach(config => {
          wx.setStorageSync(config.id, config.val);
          if (config.id === 'recharge_amount_min') {
            that.globalData.recharge_amount_min = config.val;
          }
        })
        that.globalData.order_reputation_score = 1;
      }
    })
    
  },
  getWxUser: function () {
    wx.navigateTo({
      url: "/pages/authorize/index"
    })
  },

  goStartIndexPage: function() {
    setTimeout(function() {
      wx.redirectTo({
        url: "/pages/start/start"
      })
    }, 1000)
  },  
  onShow (e) {
    const _this = this
    // 保存邀请人
    if (e && e.query && e.query.scene) {
      const scene = decodeURIComponent(e.query.scene) // 处理扫码 最后那个是用户的id
      if (scene) {
        let vals = scene.split(',');
        let ref = vals[vals.length - 1];
        wx.setStorageSync('referrer', ref);
      }
    }
    if (e && e.query && e.query.inviter_id) {
      wx.setStorageSync('referrer', e.query.inviter_id)
      // if (e.shareTicket) {
      //   // 通过分享链接进来
      //   wx.getShareInfo({
      //     shareTicket: e.shareTicket,
      //     success: res => {
      //       // console.error(res)
      //       // console.error({
      //       //   referrer: e.query.inviter_id,
      //       //   encryptedData: res.encryptedData,
      //       //   iv: res.iv
      //       // })
      //       WXAPI.shareGroupGetScore(
      //         e.query.inviter_id,
      //         res.encryptedData,
      //         res.iv
      //       )
      //     }
      //   })
      // }
    }    
    const token = wx.getStorageSync('token');
    if (!token) {
      _this.gettoken()
      return;
    }else{
      _this.doLogin();
    }
    this.globalData.launchOption = e  
  },
  doLogin:function(){
    const that = this;
    wx.login({
      success: function (res) {
        let referrer_storge = wx.getStorageSync('referrer');
        WXAPI.login({ code: res.code, refereeId: referrer_storge }).then(function (res) {
          if (res.type != 'success') {
            // 登录错误
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '无法登录，请重试',
              showCancel: false
            })
            return;
          }else{
            wx.setStorageSync('token', res.resultData.row);
            that.gettoken();
          } 
        })
      }
    })
  },
  gettoken: function () {
    const that = this;
    const token = wx.getStorageSync('token');
    if (token) {
      WXAPI.getToken(token).then(function (res) {
        if (res.resultData == null || res.resultData.row == null) {
          wx.removeStorageSync('token')
          that.doLogin();
        } else {
          // 回到原来的地方放 
          wx.setStorageSync('uid', res.resultData.row.id)
          wx.setStorageSync('yjuser', res.resultData.row)
        }
      })
      return;
    }else{
      that.doLogin();
    }
  },
  globalData: {                
    isConnected: true,
    launchOption: undefined,
    vipLevel: '0000'
  }
})